<template>
  <div class="app-container" v-loading="pageLoading">
    <el-row :gutter="10">
      <el-col :span="14">
        <div class="panel-info">
          <div class="panel-title">工艺手册</div>
          <div class="panel-body">
            <el-button type="primary" class="fr" @click="OpenMainModal" v-permission="'sopManual.add'">创建</el-button>
            <div class="filter-container">
              <el-select class="filter-item" style="width:140px;" @change="research" v-model="query.listType"
                placeholder="请选择要查看的数据" filterable clearable>
                <el-option :value="1" label="待我审批的"></el-option>
                <el-option :value="2" label="我创建的"></el-option>
              </el-select>
              <el-select class="filter-item" style="width: 180px;" v-model="query.material_id" placeholder="选择产品"
                filterable remote :remoteMethod='getMainMaterialOption' clearable @change="getList">
                <el-option v-for="(i,t) in mainMaterialoptions" :key="t" :value="i.value" :label="i.label"></el-option>
              </el-select>
              <el-select class="filter-item" style="width: 120px;" @change="getList" v-model="query.status"
                placeholder="请选择状态" filterable clearable>
                <el-option v-for="(val, key) in statusConfig" :key='key' :value="key" :label="val.name"></el-option>
              </el-select>
              <el-input style="width:140px" placeholder="输入工艺按回车" clearable prefix-icon="el-icon-search"
                class="filter-item" @keyup.enter.native="getList" @clear="getList" v-model="query.query">
              </el-input>
              <el-button class="filter-item" type="success" plain @click="getList">查询</el-button>
            </div>
            <div style="margin-bottom: 5px">
              <el-button type="warning" class="filter-item  ml-5" v-if="multiApproveArray.length>0"
                @click="openMultiModal" :loading="multiLoading" v-permission="'sopItem.edit'" plain>批量审核
              </el-button>
            </div>
            <z-table :list="listMain" :tableProps="tablePropsMain" @current-change="getItemList" :columns="columnsMain"
              @selection-change='selectionChange'>
              <template v-slot:content="v">
                <span v-if="v.key == 'status'" class="text-label" :class="statusConfig[v.row[v.key]].style">
                  {{statusConfig[v.row[v.key]].name}}
                </span>
                <span v-else-if="v.key == 'is_publish'">
                  {{v.row['is_publish']?'是':'否'}}
                </span>
                <div v-else-if="v.key=='file_list'">
                  <div v-if="v.row[v.key]">
                    <div v-for="(val) in v.row[v.key]" :key="val.id" style="display:flex;text-decoration:underline"
                      class="flex-start flexW mb10 ">
                      <a :href="$api.baseUrl.replace('api/', '') + val.url" target="page"
                        class="text-blue">{{val.name}}</a>
                    </div>
                  </div>
                </div>
              </template>
              <template v-slot:operation="v">
                <a href="#" class="text-green" @click.stop.prevent="editMain(v.row, 1)"
                  v-permission="'sopManual.add'">复制&nbsp;</a>
                <a href="#" class="text-blue" @click.stop.prevent="editMain(v.row, 2)"
                  v-permission="'sopManual.edit'">查看&nbsp;</a>
                <a href="#" class="text-red" :class="v.row.status ==0 || v.row.status ==2 ?'':'text-noclick'"
                  @click.stop.prevent="deleteMain(v.row)" v-permission="'sopManual.delete'">删除</a>
                <a href="#" class="text-gray" @click.stop.prevent="openLog(v.row)"
                  v-permission="'sopManual.delete'">查看日志</a>
              </template>
            </z-table>
            <z-pagination :pagination="paginationMain" :total="totalMain" :page.sync="query.page"
              :limit.sync="query.size" @change="getList"></z-pagination>
          </div>
        </div>
      </el-col>
      <el-col :span="10">
        <div class="panel-info" v-show="itemFlag">
          <div class="panel-title">手册工序</div>
          <div class="panel-body">
            <div style="padding:  0; min-height: 40px">
              <el-button class="fr" @click="createItem" type="primary" v-if="mainListStatus == 0 || mainListStatus ==2"
                plain>添加明细</el-button>
              <el-input style="width: 200px;margin-right:5px" placeholder="输入工序名称按回车" clearable
                prefix-icon="el-icon-search" class="filter-item" @keyup.enter.native="getDetailList"
                @clear="getDetailList" v-model="detailQuery.query">
              </el-input>
              <el-button class="filter-item " type="success" plain @click="getDetailList">查询</el-button>
              <!-- <el-button class="filter-item" type="info" plain @click="exportData" :loading="exportLoading">导出
              </el-button> -->
            </div>
            <z-table :list="list" :tableProps="tablePropsDetail" :columns="columns">
              <template v-slot:content="v">
                <div v-if="v.key=='file_list'">
                  <div v-if="v.row[v.key]">
                    <div v-for="(val) in v.row[v.key]" :key="val.id" style="display:flex;text-decoration:underline"
                      class="flex-start flexW mb10 ">
                      <a :href="$api.baseUrl.replace('api/', '') + val.url" target="page"
                        class="text-blue">{{val.name}}</a>
                    </div>
                  </div>
                </div>
              </template>
              <template v-slot:operation="v">
                <a href="#" class="text-green" :class="mainListStatus ==0 || mainListStatus ==2 ?'':'text-noclick'"
                  @click.stop.prevent="editDetail(v.row, 1)" v-permission="'sopManual.add'">复制</a>
                <a href="#" class="text-blue" @click.stop.prevent="editDetail(v.row,2)"
                  v-permission="'sopManual.edit'">查看&nbsp;</a>
                <a href="#" class="text-red" :class="mainListStatus ==0 || mainListStatus ==2 ?'':'text-noclick'"
                  @click.stop.prevent="deleteDetail(v.row)" v-permission="'sopManual.delete'">删除</a>
              </template>
            </z-table>
            <z-pagination :pagination="pagination" :total="totalDetail" :page.sync="detailQuery.page"
              :limit.sync="detailQuery.size" @change="getDetailList"></z-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
    <z-form-dialog v-move :data="bindProcess" :formProps="formPropsProcess" :fields="fieldsBind"
      :submitLoading="submitLoading" :visible.sync="editFormVisible">
      <template v-slot:extra-area>
        <div style="padding-left:140px">
          <div class="panel-info">
            <div class="panel-title">关联工艺</div>
            <div class="panel-body">
              <div class="filter-container" v-if="mainListStatus == 0 || mainListStatus ==2">
                <el-select class="filter-item" style="width: 200px;" v-model="bindProcess.type" placeholder="请选择工艺类型"
                  filterable clearable>
                  <el-option v-for="(i,t) in BindProcessTypeOption" :key='t' :value="i.value" :label="i.label">
                  </el-option>
                </el-select>
                <el-select class="filter-item" style="width: 300px;" v-model="bindProcess.ProcessId"
                  placeholder="选择工艺项进行添加" filterable remote :remoteMethod='getProcessData' clearable>
                  <el-option v-for="(i,t) in processData" :key="t" :value="i.id" :label="i.name"></el-option>
                </el-select>
                <el-button class="filter-item text-red" @click="addProcessTable" v-permission="'sopManual.add'">添加
                </el-button>
                <el-tag class="ml-10" type="info">提示：拖动表格行可进行排序</el-tag>
              </div>
              <z-table ref="dragTable" v-if="editFormVisible" :list="itemData" :tableProps="tablePropsProcess"
                :columns="columnsProcessBind" class="drag-Table">
                <template v-slot:content="v">
                  <div v-if="v.key=='file_list'">
                    <swiper @imgClick='swiperClick' :bagImgWh="46" :nodialogShow='true' :slidesPerView='3'
                      :spaceBetween="8" :videoPreview='true' :showData='v.row[v.key]' @videoClick='swiperClick'>
                    </swiper>
                  </div>
                  <span v-else>{{ v.row[v.key] }}</span>
                </template>
                <template v-slot:operation="v">
                  <el-button title="剔除该工单项" v-if="mainListStatus == 0 || mainListStatus ==2" type="danger"
                    @click="cancelProcess(v.row)" circle icon="el-icon-minus">
                  </el-button>
                  <span v-else>
                  </span>
                </template>
              </z-table>
            </div>
          </div>
        </div>
      </template>
      <template v-slot:footer>
        <el-button class="mt-20" type="primary" v-if="mainListStatus == 0 || mainListStatus ==2"
          @click.native="submitBindProcess" :loading="BindProcessLoading">确定
        </el-button>
        <span class="mt-20" type="primary" v-else>
        </span>
      </template>
    </z-form-dialog>
    <z-form-dialog v-move :name="mainTitle" :data="data" :formProps="formProps" :fields="fields"
      :submitLoading="submitLoading" :visible.sync="editMainFormVisible">
      <template v-slot:footer>
        <launch ref="launch" :draftApi="api+'saveDraft'" v-if="isLaunch" :copyFlag='mainType' :launchApi="api+'launch'"
          :callback="workflowFormatData" @workflowUpdateEmit="workflowUpdateEmit" @handCopyMain='handCopyMain'></launch>
        <approve :modle="workFlow" v-if="isApprove" :approveApi="$api.workflow+'approveforms'"
          :backApi="$api.workflow+'back'" :reSubmitApi="api+'launch'" :revokeApi="$api.workflow+'revoke'"
          :callback="workflowFormatData" @workflowUpdateEmit="workflowUpdateEmit" :rejectApi="$api.workflow+'reject'"
          :form="data">
        </approve>
      </template>
    </z-form-dialog>
    <el-dialog title="审核修改记录" :close-on-click-modal="false" :visible.sync="logShow" width="60%">
      <div>
        <approve-log v-if="logShow" :api="api+'GetLogList'" :form="data"></approve-log>
      </div>
    </el-dialog>
    <el-dialog title="批量审批" v-move :close-on-click-modal="true" :visible.sync="multiVisible" width="50%">
      <z-form :formProps="{labelWidth:'100px'}" :fields="multiFields" :data="multiData"></z-form>
      <div class="text-right">
        <el-button @click="multiVisible = false">取消</el-button>
        <el-button v-if="!formProps.disabled" type="primary" @click.native="multiApprove" :loading="multiLoading">确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog class="swiper" :visible.sync="swiperShow" destroy-on-close :show-close='false' width="70%" fullscreen>
      <div style="width:50px;height:50px;position:fixed;top:20px;right:20px;z-index:999"
        @click.stop="swiperShow = !swiperShow">
        <i class="el-icon-error t-40 text-white"></i>
      </div>
      <swiper v-if="swiperShow" :showData='swiperShowData' :initialSlide="initialSlide"></swiper>
    </el-dialog>
  </div>
</template>
<script>
import commonMixin from '@/views/_common/mixin'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { getToken } from '@/utils/auth'
import Sortable from 'sortablejs'
import launch from '@/views/components/scWorkflow/launch'
import approve from '@/views/components/scWorkflow/approve'
import approveLog from '@/views/components/scWorkflow/approveLog'
import dayjs from 'dayjs'
import { download } from '@/utils/index.js'
import swiper from '@/views/components/swiper'

export default {
  mixins: [commonMixin],
  name: 'sopManual',
  components: { UploadExcelComponent, launch, approve, approveLog, swiper },
  data: function () {
    return {
      swiperShow: false,
      swiperShowData: [],
      initialSlide: 0,
      api: this.$api.sopManual,
      name: '工艺模板',
      postForList: true,
      data: {},
      dataDetail: {},
      localFileArray: [], // 主表文件上传
      bindFileArray: [], // 绑定工艺文件上传
      mainMaterialoptions: [], // 主表产品选择
      query: {
        // 主表数据查询
        page: 1,
        size: 10,
        queryString: null,
        material_id: null,
        listType: 1,
        form_name: this.$options.name,
      },
      formProps: {
        dialogWidth: '70%',
        labelWidth: '140px',
        title: null, //dialog title
      },
      formPropsProcess: {
        dialogWidth: '70%',
        labelWidth: '140px',
        title: null, //dialog title
        destroyOnClose: true,
      },
      statusConfig: {
        0: { style: 'bg-yellow', name: '草稿' },
        1: { style: 'bg-green', name: '审批中' },
        2: { style: 'bg-red', name: '已退回' },
        3: { style: 'bg-gray', name: '已撤销' },
        4: { style: 'bg-gray', name: '已拒绝' },
        5: { style: 'bg-blue', name: '已完成' },
      },
      deleteArray: [],
      deleteArrayBindProcess: [],
      columnsMain: [
        { title: '产品料号', key: 'key_part_no' },
        { title: '产品料名', key: 'key_part_name', width: 120 },
        { title: '工艺模板名', key: 'name', width: 90 },
        { title: '工艺文件', key: 'file_list', width: 140 },
        { title: '状态', key: 'status', width: 70 },
        { title: '版本', key: 'version', width: 70 },
        { title: '即刻发布', key: 'is_publish', width: 80 },
        { title: '当前关卡', key: 'workflow_item_name', width: 130 },
        { title: '当前审核人', key: 'current_approver', width: 100 },
        { title: '创建人', key: 'create_user', width: 100 },
        { title: '创建时间', key: 'create_time', width: 120 },
        { title: '修改人', key: 'modify_user', width: 120 },
        { title: '修改时间', key: 'modify_time', width: 120 },
      ],
      columns: [
        { title: '工序名', key: 'group_name', width: 100 },
        { title: '描述', key: 'description', width: 100 },
        { title: '工艺文件', key: 'file_list', width: 100 },
        { title: '备注', key: 'remarks', width: 100 },
        { title: '创建人', key: 'create_user', width: 100 },
        { title: '创建时间', key: 'create_time', width: 100 },
      ],
      columnsProcessBind: [
        { title: '工艺类型', key: 'typeName' },
        { title: '工艺项名', key: 'name' },
        { title: '工艺项描述', key: 'description' },
        { title: '工艺项要求', key: 'requirement' },
        { title: '操作图示', key: 'file_list', width: 220, resizable: false },
        // { title: '当前审批人', key: 'current_approver', width: 140 },
        // { title: '状态', key: 'status', width: 140 },
        // { title: '创建人', key: 'create_user', width: 120 },
        // { title: '创建时间', key: 'create_time', width: 150 },
        // { title: '修改人', key: 'modify_user', width: 150 },
        // { title: '修改时间', key: 'modify_time', width: 150 },
      ],
      fields: [
        { title: '工艺模板名称', key: 'name', required: true, span: 24 },
        {
          title: '适用产品',
          key: 'material_id',
          span: 12,
          name: 'select',
          options: [],
          props: {
            filterable: true,
            remote: true,
            remoteMethod: this.getMaterialOptions,
          },
          required: true,
        },
        { title: '版本信息', key: 'version', span: 12, required: true },
        { title: '即刻发布', key: 'is_publish', span: 12, name: 'switch' },
        { title: '备注', key: 'remark', name: 'textarea', span: 24 },
        {
          title: '图纸上传',
          key: 'file_list',
          name: 'fileUploader',
          props: {
            id: 'sopUpload',
            accept: '.pdf',
            limit: 5,
            multiple: true,
            'on-change': this.uploadOnchange,
            'before-remove': this.beforeRemove,
            'on-preview': this.onPreview,
            autoUpload: false,
            action: '',
          },
          span: 12,
        },
      ],
      fieldsBind: [
        {
          title: '选择工序',
          key: 'group_id',
          span: 24,
          name: 'select',
          options: [],
          props: {
            filterable: true,
            remote: true,
            remoteMethod: this.getGroupOptions,
          },
          required: true,
        },
        { title: '描述', key: 'description', span: 24, required: true },
        { title: '备注', key: 'remarks', span: 24, name: 'textarea' },
        {
          title: '图纸上传',
          key: 'file_list',
          name: 'fileUploader',
          props: {
            id: 'sopUpload',
            accept: '.pdf',
            limit: 5,
            multiple: true,
            'on-change': this.uploadOnchangeBindProcess,
            'before-remove': this.beforeRemoveBindProcess,
            'on-preview': this.onPreview,
            autoUpload: false,
            action: '',
          },
          span: 12,
        },
      ],
      user: this.$store.state.user.user,
      processData: [], // 工艺数据
      bindProcess: {},
      initDatabindProcess: {},
      itemData: [],
      processType: null, // 是编辑还是复制
      initData: {
        file: [],
      },
      logShow: false,
      tableLogLoading: false,
      logList: [],
      tablePropsMain: {
        'highlight-current-row': true,
        border: true,
        opsColWith: '200',
        selection: {
          showSelection: true,
          props: { selectable: this.selectable },
        }, //
      },
      tablePropsDetail: {
        'highlight-current-row': true,
        border: true,
        opsColWith: '160',
        showIndexCol: true,
      },
      tablePropsProcess: {
        'highlight-current-row': true,
        border: true,
        opsColWith: '100',
        maxHeight: '300',
        rowKey: 'id',
      },
      workFlow: {
        form_name: this.$options.name,
      },
      mainListStatus: null, // 主表当前点击状态
      editMainFormVisible: false, //编辑模态框的显示状态
      listMain: [],
      multiApproveArray: [], // 多选处理
      multiLoading: false,
      multiVisible: false,
      multiFields: [{ title: '审批意见', key: 'comments', span: 24, name: 'textarea' }],
      multiData: {},
      totalMain: 0,
      detailQuery: {
        page: 1,
        size: 10,
        manual_id: null,
      },
      BindProcessLoading: false,
      BindProcessTypeOption: [],
      totalDetail: 0,
      itemFlag: false,
      mainType: '',
      mainTitle: '',
      copydo: null, // 复制的时候操作的是什么
      paginationMain: {
        //分页组件配置 如不需分页，可以把pagination设置为null
        layout: 'prev, pager, next, jumper, ->, total, sizes',
      },
      pagination: {
        //分页组件配置 如不需分页，可以把pagination设置为null
        layout: 'prev, pager, next, ->, total',
      },
    }
  },
  computed: {
    isApprove() {
      if (this.mainType == 1) {
        return false
      } else {
        return this.data.status == 5 || this.data.status == 1 || this.data.status == 2
      }
    },
    isLaunch() {
      if (this.mainType == 1) {
        return true
      } else {
        return this.data.status == 0 || !this.data.status
      }
    },
  },
  methods: {
    // 多选过滤
    selectable(row) {
      if (row.current_approver) {
        let approverArray = row.current_approver.split(',')
        return row.status == 1 && approverArray.indexOf(this.user.userID) > -1
      }
      return false
    },
    // 多选处理
    selectionChange(val) {
      this.multiApproveArray = []
      val.forEach((v) => {
        this.multiApproveArray.push({ id: v.id, form_name: v.form_name, comments: '' })
      })
    },
    getMaterialOptions(str) {
      this.$request(this.$api.sku + 'getlist', { queryString: str, page: 1, size: 99 }).then((r) => {
        this.setFieldOptions('material_id', r.list, 'id', ['key_part_no', 'key_part_name'])
      })
    },
    getMainMaterialOption(str) {
      this.$request(this.$api.sku + 'getlist', { queryString: str, page: 1, size: 50 }).then((r) => {
        this.mainMaterialoptions = r.list.map((x) => {
          return { value: x.id, label: x.key_part_no + ' ' + x.key_part_name }
        })
      })
    },
    // 审核
    openMultiModal() {
      this.multiData = {}
      if (this.multiApproveArray.length <= 0) {
        this.$message.error('请先勾选要审批的记录')
        return false
      }
      this.multiVisible = true
    },
    // 批量审批
    multiApprove() {
      if (this.multiApproveArray.length <= 0) {
        this.$message.error('请先勾选要审批的记录')
        return false
      }
      this.multiApproveArray.forEach((v) => {
        v.comments = this.multiData.comments
      })
      this.multiLoading = true
      this.$request(this.$api.workflow + 'approveforms', this.multiApproveArray, 'post')
        .then((r) => {
          this.$message.success('批量审批成功')
          this.getList()
        })
        .finally(() => {
          this.multiLoading = false
          this.multiVisible = false
        })
    },
    getGroupOptions(str) {
      this.$request(this.$api.group + 'getlist', { queryString: str, page: 1, size: 99 }).then((r) => {
        let tmp = this.fieldsBind.find((x) => x.key == 'group_id')
        tmp.options = r.map((x) => {
          return { value: x.id, label: x.group_name }
        })
      })
    },
    workflowFormatData(fileData) {
      let file = fileData || this.localFileArray
      let tmp = ''
      //草稿或退回状态
      if (!this.data.status || this.data.status == 0 || this.data.status == 2 || this.copydo == 1) {
        let form = new FormData()
        let check = this.validataData(this.fields, this.data)
        if (!check) return false
        let log = ''
        if (this.dataDetail.id) {
          for (let k in this.data) {
            if (this.data[k] !== this.dataDetail[k] && k !== 'file_list') {
              let key = this.fields.find((x) => x.key == k).title
              if (!!key) {
                log = log + key + ':' + this.dataDetail[k] + ';'
              }
            }
          }
        }
        let data = {
          workflowData: this.workFlow,
          baseData: this.data,
          logData: { content: log },
          deleteArray: this.deleteArray,
        }
        if (this.mainType == 1) {
          data['faqi'] = this.copydo
          delete data.logData
        }
        form.append('model', JSON.stringify(data))
        file &&
          file.forEach((v) => {
            form.append('files', v)
          })
        tmp = form
      } else {
        tmp = this.workFlow
      }
      return tmp
    },
    handCopyMain(flag) {
      this.copydo = flag
      let data = this.workflowFormatData()
      this.$request(this.api + 'copymain', data, 'post').then((r) => {
        this.$message.success('复制成功')
        if (flag == 1) this.$refs.launch._data.draftLoading = false
        else this.$refs.launch._data.submitLoading = false
        this.workflowUpdateEmit()
      })
    },
    workflowUpdateEmit() {
      this.getList()
      this.editMainFormVisible = false
    },
    getList() {
      this.pageLoading = true
      let url = this.api + 'getlist'
      this.$request(url, this.formatQuery(this.query), 'post')
        .then((r) => {
          this.itemFlag = false
          this.list = []
          this.listMain = this.formatList(r.list)
          this.totalMain = r.total
        })
        .finally(() => {
          this.pageLoading = false
        })
    },
    getItemList(v) {
      // this.itemFlag = false
      if (!v) return
      this.detailQuery.manual_id = v.id
      this.mainListStatus = v.status
      this.getDetailList()
    },
    editMain(v, type) {
      this.mainType = type
      this.formProps.title = type == 1 ? '复制工艺手册' : '编辑工艺手册'
      this.pageLoading = true
      this.$request(this.api + 'getbyid?id=' + v.id + '&formName=' + this.$options.name)
        .then((r) => {
          let tmp = _.cloneDeep(this.formatAfterGet(r))
          let tmp2 = _.cloneDeep(this.formatAfterGet(r))
          this.pageLoading = false
          this.data = tmp
          this.dataDetail = tmp2
          this.editMainFormVisible = true
          this.deleteArray = []
          this.localFileArray = []
          if (type == 2) {
            let booltmp =
              this.data.status == 0 ||
              !this.data.status ||
              (this.data.status == 2 && this.data.create_user == this.user.userID)
            this.setFieldsDisable(!booltmp, ['name', 'material_id', 'version', 'is_publish', 'file_list', 'remark'])
          } else {
            this.setFieldsDisable(false, ['name', 'material_id', 'version', 'is_publish', 'file_list', 'remark'])
          }
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    formatAfterGet(data) {
      this.getMaterialOptions(data.material_name)
      return data
    },
    OpenMainModal() {
      this.data = _.cloneDeep(this.initData)
      this.mainType = 2
      this.formProps.title = '创建工艺手册'
      this.mainDisable = false
      this.editMainFormVisible = true
      this.localFileArray = []
      this.dataDetail = {}
      this.setFieldsDisable(false, ['name', 'material_id', 'version', 'is_publish', 'file_list', 'remark'])
      this.$nextTick(() => {
        let idUp = document.getElementById('sopUpload')
        idUp.__vue__.clearFiles()
      })
    },
    deleteMain(v) {
      if (v.status != 0 && v.status != 2) {
        return
      }
      this.$confirm('确定要删除 ' + v.name + ' 这条记录？', '操作确认').then(() => {
        this.pageLoading = true
        let url = this.api + 'deletemain'
        this.$request(url + '/' + v.id + '/' + this.$options.name, {}, 'post')
          .then((r) => {
            this.pageLoading = false
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.getList()
          })
          .catch(() => {
            this.pageLoading = false
          })
      })
    },
    // 打开日志
    openLog(row) {
      this.data = row
      this.logShow = true
    },
    // 明细表处理
    getDetailList() {
      this.$request(this.api + 'getdetaillist', this.detailQuery, 'post')
        .then((r) => {
          this.list = r.list
          this.totalDetail = r.total
        })
        .finally(() => {
          this.itemFlag = true
        })
    },
    // 预览点击
    swiperClick(data, t) {
      this.swiperShowData = data
      this.initialSlide = t
      this.swiperShow = true
    },
    formatListBindProcess(data) {
      let tmp = _.cloneDeep(data)
      tmp.forEach((i) => {
        i.file_list.forEach((k) => {
          k.type = this.getFileType(k.url)
          k.url = this.$api.baseUrl.replace('api/', '') + k.url
        })
        this.BindProcessTypeOption.map((j) => {
          if (i.type == j.value) {
            i.typeName = j.label
            i.id = i.id || i.item_id
          }
        })
      })
      return tmp
    },
    createItem() {
      this.processType = 2
      this.bindProcess = _.cloneDeep(this.initDatabindProcess)
      this.editFormVisible = true
      this.bindFileArray = []
      this.itemData = []
      this.setFieldsDisable(false, ['group_id', 'description', 'remarks', 'file_list'], this.fieldsBind)
      this.$nextTick(() => {
        this.initSortable()
        let idUp = document.getElementById('sopUpload')
        idUp.__vue__.clearFiles()
      })
    },
    getProcessData(val) {
      this.$request(
        this.$api.sopItem + 'getList',
        { query: val, type: this.bindProcess.type, page: 1, size: 99, form_name: 'sopItem', status: 5 },
        'post',
      ).then((r) => {
        this.processData = this.formatListProcess(r.list)
      })
    },
    getFileType(url) {
      var spl = url.split('.')
      return spl[spl.length - 1]
    },
    formatListProcess(data) {
      let tmp = _.cloneDeep(data)
      tmp.forEach((i) => {
        i.file_list.forEach((k) => {
          k.type = this.getFileType(k.url)
          k.url = this.$api.baseUrl.replace('api/', '') + k.url
        })
      })
      return tmp
    },
    editDetail(data, v) {
      if (v == 1) {
        if (this.mainListStatus != 0 && this.mainListStatus != 2) {
          return
        }
      }
      this.formPropsProcess.title = v == 1 ? '复制手册工序' : '编辑手册工序'
      this.processType = v
      this.editFormVisible = true
      this.$request(this.api + 'getdetailbyid?id=' + data.id).then((r) => {
        this.bindProcess = this.formatDetailAfterGet(r)
        // this.bindProcessDetail =
        this.itemData = this.formatListBindProcess(this.bindProcess.itemData)
        if (v == 1) {
          delete this.bindProcess.id
          this.setFieldsDisable(false, ['group_id', 'description', 'remarks', 'file_list'], this.fieldsBind)
        } else {
          let booltmp = this.mainListStatus == 0 || !this.mainListStatus || this.mainListStatus == 2
          this.setFieldsDisable(!booltmp, ['group_id', 'description', 'remarks', 'file_list'], this.fieldsBind)
        }
        this.$nextTick(() => {
          this.initSortable()
        })
        this.getProcessData(r.group_name || '')
        this.deleteArrayBindProcess = []
        this.bindFileArray = []
      })
    },
    formatDetailAfterGet(data) {
      let tmp = _.cloneDeep(data)
      this.getGroupOptions(tmp.group_name)
      return tmp
    },
    deleteDetail(v) {
      if (this.mainListStatus != 0 && this.mainListStatus != 2) {
        return
      }
      this.$confirm('确定要删除 ' + v.group_name + ' 这条记录？', '操作确认').then(() => {
        this.pageLoading = true
        let url = this.api + 'deletedetail'
        this.$request(url + '/' + v.id + '/' + this.$options.name, {}, 'post')
          .then((r) => {
            this.pageLoading = false
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.getDetailList()
          })
          .catch(() => {
            this.pageLoading = false
          })
      })
    },
    addProcessTable() {
      if (!this.bindProcess.ProcessId) return
      let tmp = this.processData.find((x) => x.id == this.bindProcess.ProcessId)
      tmp = this.formatListBindProcess([tmp])[0]
      if (!this.itemData.some((i) => i.id == tmp.id)) {
        this.itemData.push(tmp)
      } else {
        this.$message.error('该工艺已经关联')
      }
    },
    onPreview(file) {
      if (file.url && (file.url.indexOf('http://') > -1 || file.url.indexOf('https://')))
        download(this.$api.baseUrl, file)
    },
    uploadOnchange(file, fileList) {
      let f = file.raw
      if (f.type == 'application/pdf') {
        if (f.size < 40 * 1024 * 1024) {
          this.localFileArray.push(f)
        } else {
          this.$message.error('pdf 大小限制40M')
          fileList.splice(fileList.indexOf(f), 1)
        }
      }
    },
    uploadOnchangeBindProcess(file, fileList) {
      let f = file.raw
      if (f.type == 'application/pdf') {
        if (f.size < 40 * 1024 * 1024) {
          this.bindFileArray.push(f)
        } else {
          this.$message.error('pdf 大小限制40M')
          fileList.splice(fileList.indexOf(f), 1)
        }
      }
    },
    beforeRemove(file) {
      if (file.id) {
        this.deleteArray.push(file.id)
        let fileArray = this.data.file_ids.split(',')
        let fileArrayTmp = fileArray.filter((v) => {
          return v != file.id
        })
        this.data.file_ids = fileArrayTmp.join(',')
      } else {
        this.localFileArray = this.localFileArray.filter((v) => {
          return v.uid != file.uid
        })
      }
    },
    beforeRemoveBindProcess(file) {
      if (file.id) {
        this.deleteArrayBindProcess.push(file.id)
        let fileArray = this.bindProcess.file_ids.split(',')
        let fileArrayTmp = fileArray.filter((v) => {
          return v != file.id
        })
        this.bindProcess.file_ids = fileArrayTmp.join(',')
      } else {
        this.bindFileArray = this.bindFileArray.filter((v) => {
          return v.uid != file.uid
        })
      }
    },
    initSortable() {
      let _this = this
      // 获取表格row的父节点
      const ele = this.$refs.dragTable.$el.querySelector('.el-table__body > tbody')
      // 创建拖拽实例
      let dragTable = Sortable.create(ele, {
        animation: 150, //动画
        disabled: false,
        // 开始拖动事件
        onStart: () => {},
        // 结束拖动事件
        onEnd: ({ newIndex, oldIndex }) => {
          const currRow = _this.itemData.splice(oldIndex, 1)[0] //当前行
          _this.itemData.splice(newIndex, 0, currRow)
        },
      })
    },
    // 剔除工单项
    cancelProcess(v) {
      this.$confirm('此操作将剔除 ' + v.name + ' 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.itemData.splice(this.itemData.indexOf(v), 1)
      })
    },
    submitBindProcess() {
      this.BindProcessLoading = true
      let addUrl = this.processType == 1 ? 'copydetail' : 'insertorupdatedetail'
      let tmp = _.cloneDeep(this.bindProcess)
      let baseData = Object.assign({}, tmp)
      baseData['manual_id'] = this.detailQuery.manual_id
      let itemData = this.itemData.map((i, t) => {
        return {
          item_id: i.id || i.item_id,
          seq: t,
        }
      })
      let data = { baseData, form_name: this.$options.name, itemData, deleteArray: this.deleteArrayBindProcess }
      let form = new FormData()
      let check = this.validataData(this.fieldsBind, this.bindProcess)
      if (!check) return false
      form.append('model', JSON.stringify(data))
      this.bindFileArray &&
        this.bindFileArray.forEach((v) => {
          form.append('files', v)
        })
      this.$request(this.api + addUrl, form, 'post')
        .then((r) => {
          this.$message.success('操作成功')
          this.editFormVisible = false
          this.getDetailList()
        })
        .finally(() => {
          this.BindProcessLoading = false
        })
    },
  },
  watch: {},
  created: function () {
    this.$request(this.$api.workflow + 'GetWorkFlowIdByPage?formName=' + this.$options.name).then((r) => {
      this.workFlow = {
        form_name: this.$options.name,
      }
    })
    this.$request(this.$api.dictionary + 'getdirectchildren', {
      parentType: 'process_type',
    }).then((r) => {
      this.BindProcessTypeOption = r
    })
    this.getList()
  },
  mounted() {},
}
</script>
<style scoped>
.swiper ::v-deep .el-dialog {
  background-color: rgba(0, 0, 0, 0);
  padding: 30px 100px 0;
  box-sizing: border-box;
  /* height: 100%; */
}
.swiper ::v-deep .el-dialog__header {
  padding: 0;
}
.swiper ::v-deep .el-dialog__body {
  padding: 0;
  background-color: rgba(0, 0, 0, 0.001);
}
</style>
